package rad.framework.mda.jpagen.actions;

import rad.framework.mda.generator.Console;
import rad.framework.mda.generator.util.ClassHelper;
import rad.framework.mda.util.ModelUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;

/**
 * @author boudyacho
 * 
 */
public class AddUniqueNaturalActionExtension extends BaseUtiltiyActionExtension {

	protected static final String UNIQUE = "rad.framework.validator.Unique";

	protected static final String UNIQUE_PROPERTIES = "rad.framework.validator.UniqueProperties";

	protected static final String NATURAL_ID = "org.hibernate.annotations.NaturalId";

	public void fillContextMenu(IMenuManager aMenu) {
		getSubMenu(aMenu).add(new AddUniqueNaturalAction());
	}

	protected void execute(Class clazz) {
		if (ModelUtil.isStereotypeApplied(clazz, ENTITY)) {
			EList<NamedElement> list = clazz.getMembers();
			for (NamedElement namedElement : list) {
				if (namedElement instanceof Property) {
					execute((Property) namedElement);
				}
			}
		}
	}

	protected void execute(Property property) {
		if (!ModelUtil.isStereotypeApplied(property, NATURAL_ID)) {
			String names = "name,code";
			if (names.contains(property.getName())
					|| ClassHelper.isMyParent(property)) {
				addNaturalId(property);
				addUnique((NamedElement) property.getOwner());
				Console.getStream().println(
						"Added Natural Id - " + property.getQualifiedName());
			}
		}
	}

	protected void addNaturalId(Element element) {
		Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
				element, NATURAL_ID);
		if (stereotype != null) {
			element.applyStereotype(stereotype);
			element.setValue(stereotype, "mutable", "true");
		}
	}

	protected void addUnique(NamedElement element) {
		if (!ModelUtil.isStereotypeApplied(element, UNIQUE)
				&& !ModelUtil.isStereotypeApplied(element, UNIQUE_PROPERTIES)) {
			Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
					element, UNIQUE);
			if (stereotype != null) {
				element.applyStereotype(stereotype);
				Console.getStream().println(
						"Added Unique - " + element.getQualifiedName());
			}
		}
	}

	private class AddUniqueNaturalAction extends BaseUtilityAction {
		private static final String LABEL = "Add Unique/Natural Id Stereotypes";

		public AddUniqueNaturalAction() {
			super(LABEL);
		}
	}
}
